package com.cy.module;

import com.cy.BasicController;
import com.cy.ext.plugin.route.ControllerBind;
import com.jfinal.plugin.activerecord.Model;
import org.apache.commons.beanutils.MethodUtils;
import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.reflect.FieldUtils;

import java.util.HashMap;

/**
 * 页面选项
 */
@ControllerBind(controllerKey = "/item")
public class ItemController extends BasicController {

    //默认后缀
    private static final String SUFFIX = "Items";

    public void index(){
        String[] classNames = getParaValues("className[]");
        String suffix = getPara("suffix");
        if (StringUtils.isBlank(suffix))
            suffix = SUFFIX;
        HashMap<String, Object> json = new HashMap<>();
        for (String className : classNames){
            try {
                Class<?> c = ClassUtils.getClass(className, false);
                if (!Model.class.isAssignableFrom(c))
                    throw new RuntimeException(c.getName() +" is not com.jfinal.plugin.activerecord.Model's subclass!");
                Object daoObject = FieldUtils.readDeclaredStaticField(c, "dao");
                Object result = MethodUtils.invokeMethod(daoObject, "findAll", null);
                String key = StringUtils.uncapitalize(c.getSimpleName()).concat(suffix);
                json.put(key, result);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        renderJson(json);
    }
}